import React, { Component } from 'react'
import { Link } from 'react-router'
import Picker from 'react-mobile-picker-scroll'
import { isEmpty, isUndefined } from 'lodash/fp'
import { message } from 'antd'
var FormData = require('form-data')

import s from '../assets/Article.scss'
import { bindWechat } from 'tools/bindWechat'

class Article extends Component {
  constructor (props, context) {
    super(props, context)
    this.handleChange = this.handleChange.bind(this)
    this.hiddenTypeSelect = this.hiddenTypeSelect.bind(this)
    this.state = {
      articleTitle: '',
      articleType: '发帖类型',
      articleProfile: '',
      articleTypeSelect: false,
      valueGroups: {
        title: ''
      },
      optionGroups: {
        title: []
      },
      responseImg: [],
      responseImgShow: [],
      imgArr: []
    }
  }

  componentDidMount () {
    bindWechat('发帖', 'V3EX')
    const { fetchForumType } = this.props
    fetchForumType()
  }

  componentWillUnmount () {

  }

  componentWillReceiveProps (nextProps) {
    const { addArticle } = nextProps
    const { forumType, articleAct, fileUpload } = addArticle
    const { type } = forumType
    const { upload, isFetching } = fileUpload

    if (!isUndefined(forumType) && !isUndefined(type) && !isUndefined(type.result) && !isUndefined(type.result.data) && type.result.data.length > 0 && forumType.isFetching !== this.props.addArticle.forumType.isFetching) {
      let data = []
      type.result.data.map((item, i) => {
        data.push(item.c_name)
      })
      this.setState({
        valueGroups: {
          title: data[0]
        },
        optionGroups: {
          title: data
        }
      })
    }
    // upload
    if (!isUndefined(fileUpload) && !isUndefined(upload) && !isUndefined(upload.err_msg) && isFetching !== this.props.addArticle.fileUpload.isFetching) {
      let arr = JSON.parse(upload.err_msg)
      if (this.state.imgArr.length < 10) {
        this.setState({
          imgArr: [...this.state.imgArr, arr.filename.url]
        })
      }
    }
    if (!isUndefined(forumType) && !isUndefined(articleAct) && !isUndefined(articleAct.article) && !isUndefined(articleAct.article.result) && !isUndefined(articleAct.article.result.data) && articleAct.article.result.data === 'success' && articleAct.isFetching !== this.props.addArticle.articleAct.isFetching) {
      message.success('发帖成功！')
      this.context.router.push('/')
    }
  }

  getInput (e) {
    let value = e.target.value
    switch (e.target.id) {
      case 'articleTitle':
        if (value.length > 30) break
        this.setState({
          articleTitle: value
        })
        break
      case 'articleProfile':
        if (value.length > 500) break
        this.setState({
          articleProfile: value
        })
        break
      default:
    }
  }

  handleChange = (name, value) => {
    this.setState(({valueGroups}) => ({
      valueGroups: {
        ...valueGroups,
        [name]: value
      }
    }))
    this.setState({
      articleType: value,
      articleTypeSelect: false
    })
  }

  articleTypeSelect () {
    this.setState({
      articleTypeSelect: true
    })
  }

  hiddenTypeSelect () {
    this.setState({
      articleTypeSelect: false
    })
  }

  publishArticle () {
    let title = this.refs.articleTitle.value
    let type = this.state.articleType
    let profile = this.refs.articleProfile.value
    const { user, fetchArticle } = this.props
    const { signed } = user
    if (title  === '') {
      message.warning('帖子的标题呢？')
      return
    } else if (type === '发帖类型') {
      message.warning('这个帖子类型？')
      return
    } else if (profile === '') {
      message.warning('帖子的内容呢？')
      return
    } else if (!isUndefined(user.signed) && !isUndefined(user.signed.result) && !isUndefined(user.signed.result.userdata) && !isUndefined(user.signed.result.userdata.u_id)) {
      let c_id = 0
      this.state.optionGroups.title.map((item, i) => {
        if (this.state.optionGroups.title[i] === this.state.articleType) {
          c_id = i + 1
        }
      })
      fetchArticle (user.signed.result.userdata.u_id, c_id, title, profile, this.state.imgArr)
    }
  }

  deletePicture (i) {
    let arr = this.state.imgArr
    arr.splice(i, 1)
    this.setState({
      imgArr: arr,
    })
  }

  upload() {
    const { fileUpload } = this.props
    let myFile = this.refs.myFile.files[0]
    var form = new FormData()
    form.append('filename', myFile)
    fileUpload(form)
  }

  render () {
    const { addArticle } = this.props
    const { forumType } = addArticle
    return (
      <div className={s.articleContent}>
        <input type='text' id='articleTitle' ref='articleTitle' className={s.articleTitle} placeholder='发帖标题' value={this.state.articleTitle} onChange={e => this.getInput(e)} />
        <p className={s.type} onClick={e => this.articleTypeSelect(e)}>{this.state.articleType}</p>
        <div className={s.uploadPhotos}>
          { !isEmpty(this.state.imgArr) && this.state.imgArr.length > 0 &&
              <div className={s.picture}>
                {this.state.imgArr.map((item, i) =>
                  <div className={s.pictureList} key={i}>
                    <a href="javascript:;" onClick={() => this.deletePicture(i)}></a>
                    <img src={item} />
                  </div>
                )}
              </div>
            }
          <div className={s.photosBack}>
            <div id='container' className={s.upload}>
              <input type='file' id='fileId' ref='myFile' accept='image/png,image/image/jpeg,image/image/jpg' onChange={(e) => this.upload(e)} />
            </div>
          </div>
          <p>上传图片(最多10张)</p>
        </div>
        <textarea
          placeholder='发帖内容'
          id='articleProfile'
          className={s.articleProfile}
          ref='articleProfile'
          maxLength='200'
          value={this.state.articleProfile}
          onChange={e => this.getInput(e)}>{this.state.personalProfile}</textarea>
        { this.state.articleTypeSelect &&
          <div className={s.aic}>
            <div className={s.see} onClick={this.hiddenTypeSelect}></div>
            <div className={s.articleTypeSelect}>
              <Picker optionGroups={this.state.optionGroups} valueGroups={this.state.valueGroups} onChange={this.handleChange} />
            </div>
          </div>
        }
        <a href='javascript:;' onClick={() => this.publishArticle()}>发送内心的独白</a>
      </div>
    )
  }
}

Article.propTypes = {

}

Article.contextTypes = {
  router: React.PropTypes.object.isRequired
}


export default Article
